#include <iostream>
#include <string>
#include <cstdlib>
#include <cstdio>
#include <thread>
#include <WinSock2.h>
#include <Windows.h>
#pragma warning(disable : 4996)    // 关闭不必要的警报
#pragma comment(lib, "ws2_32.lib") // 引入Windows下的库

static const std::string gserverip = "113.44.141.138";
static const uint16_t gserverport = 8080;
int main()
{
    // 设置版本号
    WSADATA wsd;
    WSAStartup(MAKEWORD(2, 2), &wsd);
    // 创建套接字
    SOCKET sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == INVALID_SOCKET)
    {
        std::cout << "socket filed" << std::endl;
        WSACleanup();
        return 1;
    }
    std::cout << "socket success,socket:" << sockfd << std::endl;
    // 填充网络信息
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(gserverport);
    server.sin_addr.s_addr = inet_addr(gserverip.c_str());
    // 客户端不需要显式进行绑定
    // 进行连接
    int n = connect(sockfd, (sockaddr *)&server, sizeof(server));
    if (n < 0)
    {
        std::cout << "connect filed" << std::endl;
        WSACleanup();
        return 2;
    }
    std::cout << "connect success.sockfd:" << sockfd << std::endl;
    // 连接成功后进行通信
    std::string message;
    char inbuffer[1024];
    while (true)
    {
        std::cout << "please enter#";
        std::getline(std::cin, message);
        int m = send(sockfd, message.c_str(), message.size(), 0);
        if (m > 0)
        {
            int s = recv(sockfd, inbuffer, sizeof(inbuffer) - 1, 0);
            if (s > 0)
            {
                inbuffer[s] = 0;
                std::cout << inbuffer << std::endl;
            }
        }
    }
    // 释放库资源
    closesocket(sockfd);
    WSACleanup();
    return 0;
}
